'use client'

import { zodResolver } from '@hookform/resolvers/zod';
import React, { useState } from 'react'
import { useForm } from 'react-hook-form';
import * as z from "zod";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '../ui/form';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { signUp } from '@/lib/auth-client';
import { toast } from "sonner"

const registerSchema = z.object({
    name: z.string().min(3, 'Name is required'),
    email: z.string().email('Invalid email address'),
    password: z.string().min(6, 'Password must be at least 6 characters'),
    confirmPassword: z.string().min(6, 'Password must be at least 6 characters'),
}).refine((data) => data.password === data.confirmPassword, {
    message: "Passwords don't match",
    path: ["confirmPassword"],
})

type RegisterFormvalues = z.infer<typeof registerSchema>

const RegisterFormInfo: { name: keyof RegisterFormvalues, label: string, type?: string }[] = [
    {
        name: 'name',
        label: 'Name',
    },
    {
        name: 'email',
        label: 'Email',
    },
    {
        name: 'password',
        label: 'Password',
        type: 'password',
    }, {
        name: 'confirmPassword',
        label: 'Confirm Password',
        type: 'password',
    }]

interface RegisterFormProps {
    onSuccess: () => void
}


export default function RegisterForm({ onSuccess }: RegisterFormProps) {
    const [isLoading, setIsLoading] = useState(false)

    const form = useForm<RegisterFormvalues>({
        resolver: zodResolver(registerSchema),
        defaultValues: {
            name: "",
            email: "",
            password: "",
            confirmPassword: "",
        },
    })

    const onSubmit = async (values: RegisterFormvalues) => {
        setIsLoading(true)
        try {
            const { error } = await signUp.email({
                name: values.name,
                email: values.email,
                password: values.password
            })
            if (error) {
                toast('Failed to register')
                return
            }
            toast('Successfully registered')
            onSuccess()
        } catch (error) {
            console.log(error)
        } finally {
            setIsLoading(false)
        }
    }

    return (
        <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">

                {RegisterFormInfo.map((item) => {
                    return (
                        <FormField
                            key={item.name}
                            control={form.control}
                            name={item.name}
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>{item.label}</FormLabel>
                                    <FormControl>
                                        <Input type={item.type || 'text'} {...field} />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />
                    )
                })}

                <Button type="submit" className='w-full cursor-pointer' disabled={isLoading}>{isLoading ? '...' : 'Submit'}</Button>
            </form>
        </Form>
    )
}
